//
//  TestResultViewController.m
//  GCDBenchmark
//
//  Created by Claude on 2025/10/13.
//

#import "TestResultViewController.h"

@interface TestResultViewController ()
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic, strong) UITextView *resultTextView;
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicator;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, assign) BOOL testCompleted;
@end

@implementation TestResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.testCompleted = NO;
    [self setupUI];
    [self animateIn];
}

- (void)setupUI {
    // 半透明背景
    self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTapped:)];
    [self.view addGestureRecognizer:tapGesture];

    // 容器视图
    self.containerView = [[UIView alloc] init];
    self.containerView.backgroundColor = [UIColor systemBackgroundColor];
    self.containerView.layer.cornerRadius = 16;
    self.containerView.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    self.containerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.containerView];

    // 拖动手柄
    UIView *handleView = [[UIView alloc] init];
    handleView.backgroundColor = [UIColor tertiaryLabelColor];
    handleView.layer.cornerRadius = 2.5;
    handleView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.containerView addSubview:handleView];

    // 标题
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.font = [UIFont systemFontOfSize:20 weight:UIFontWeightBold];
    self.titleLabel.text = [NSString stringWithFormat:@"%@ %@", self.testIcon ?: @"", self.testName ?: @"测试"];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.containerView addSubview:self.titleLabel];

    // 关闭按钮
    self.closeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.closeButton setTitle:@"✕" forState:UIControlStateNormal];
    self.closeButton.titleLabel.font = [UIFont systemFontOfSize:24];
    [self.closeButton addTarget:self action:@selector(closeButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.closeButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.containerView addSubview:self.closeButton];

    // 状态标签
    self.statusLabel = [[UILabel alloc] init];
    self.statusLabel.font = [UIFont systemFontOfSize:15];
    self.statusLabel.textColor = [UIColor secondaryLabelColor];
    self.statusLabel.text = @"正在运行测试...";
    self.statusLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.containerView addSubview:self.statusLabel];

    // 活动指示器
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleMedium];
    self.activityIndicator.hidesWhenStopped = YES;
    self.activityIndicator.translatesAutoresizingMaskIntoConstraints = NO;
    [self.containerView addSubview:self.activityIndicator];

    // 结果文本视图
    self.resultTextView = [[UITextView alloc] init];
    self.resultTextView.font = [UIFont monospacedSystemFontOfSize:14 weight:UIFontWeightRegular];
    self.resultTextView.textColor = [UIColor labelColor];
    self.resultTextView.backgroundColor = [UIColor secondarySystemBackgroundColor];
    self.resultTextView.layer.cornerRadius = 8;
    self.resultTextView.editable = NO;
    self.resultTextView.textContainerInset = UIEdgeInsetsMake(12, 12, 12, 12);
    self.resultTextView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.containerView addSubview:self.resultTextView];

    if (self.isRunning) {
        [self.activityIndicator startAnimating];
        self.closeButton.enabled = NO;
        self.closeButton.alpha = 0.3;
    }

    // 设置约束
    [NSLayoutConstraint activateConstraints:@[
        // 容器视图
        [self.containerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.containerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.containerView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
        [self.containerView.heightAnchor constraintEqualToConstant:400],

        // 手柄
        [handleView.topAnchor constraintEqualToAnchor:self.containerView.topAnchor constant:8],
        [handleView.centerXAnchor constraintEqualToAnchor:self.containerView.centerXAnchor],
        [handleView.widthAnchor constraintEqualToConstant:40],
        [handleView.heightAnchor constraintEqualToConstant:5],

        // 标题
        [self.titleLabel.topAnchor constraintEqualToAnchor:handleView.bottomAnchor constant:16],
        [self.titleLabel.leadingAnchor constraintEqualToAnchor:self.containerView.leadingAnchor constant:20],
        [self.titleLabel.trailingAnchor constraintEqualToAnchor:self.closeButton.leadingAnchor constant:-8],

        // 关闭按钮
        [self.closeButton.centerYAnchor constraintEqualToAnchor:self.titleLabel.centerYAnchor],
        [self.closeButton.trailingAnchor constraintEqualToAnchor:self.containerView.trailingAnchor constant:-16],
        [self.closeButton.widthAnchor constraintEqualToConstant:44],
        [self.closeButton.heightAnchor constraintEqualToConstant:44],

        // 状态标签
        [self.statusLabel.topAnchor constraintEqualToAnchor:self.titleLabel.bottomAnchor constant:8],
        [self.statusLabel.leadingAnchor constraintEqualToAnchor:self.containerView.leadingAnchor constant:20],

        // 活动指示器
        [self.activityIndicator.centerYAnchor constraintEqualToAnchor:self.statusLabel.centerYAnchor],
        [self.activityIndicator.leadingAnchor constraintEqualToAnchor:self.statusLabel.trailingAnchor constant:8],

        // 结果文本视图
        [self.resultTextView.topAnchor constraintEqualToAnchor:self.statusLabel.bottomAnchor constant:16],
        [self.resultTextView.leadingAnchor constraintEqualToAnchor:self.containerView.leadingAnchor constant:20],
        [self.resultTextView.trailingAnchor constraintEqualToAnchor:self.containerView.trailingAnchor constant:-20],
        [self.resultTextView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant:-20],
    ]];
}

- (void)animateIn {
    // 初始位置在屏幕下方
    self.containerView.transform = CGAffineTransformMakeTranslation(0, 400);
    self.view.alpha = 0;

    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.containerView.transform = CGAffineTransformIdentity;
        self.view.alpha = 1;
    } completion:nil];
}

- (void)animateOut:(void (^)(void))completion {
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.containerView.transform = CGAffineTransformMakeTranslation(0, 400);
        self.view.alpha = 0;
    } completion:^(BOOL finished) {
        if (completion) {
            completion();
        }
    }];
}

- (void)prepareForTestWithName:(NSString *)name icon:(NSString *)icon {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.testName = name ?: @"";
        self.testIcon = icon ?: @"";
        self.isRunning = YES;
        self.testCompleted = NO;

        self.titleLabel.text = [NSString stringWithFormat:@"%@ %@", self.testIcon ?: @"", self.testName.length > 0 ? self.testName : @"测试"];
        self.statusLabel.text = @"正在运行测试...";
        self.resultTextView.text = @"测试进行中...\n";

        [self.activityIndicator startAnimating];
        self.closeButton.enabled = NO;
        self.closeButton.alpha = 0.3;
    });
}

- (void)updateProgress:(NSString *)message {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.statusLabel.text = message;
        self.resultTextView.text = [NSString stringWithFormat:@"测试进行中...\n\n%@", message];
    });
}

- (void)showResult:(NSString *)result duration:(NSTimeInterval)duration {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.activityIndicator stopAnimating];
        self.statusLabel.text = [NSString stringWithFormat:@"测试完成 - 耗时: %.3f 秒", duration];
        self.resultTextView.text = result;

        // 测试完成，启用关闭按钮
        self.isRunning = NO;
        self.testCompleted = YES;
        self.closeButton.enabled = YES;
        self.closeButton.alpha = 1.0;
    });
}

- (void)closeButtonTapped:(UIButton *)sender {
    // 只有测试完成后才能关闭
    if (!self.testCompleted) {
        return;
    }

    [self animateOut:^{
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}

- (void)backgroundTapped:(UITapGestureRecognizer *)gesture {
    // 只有测试完成后才能通过点击背景关闭
    if (!self.testCompleted) {
        return;
    }

    CGPoint location = [gesture locationInView:self.view];
    if (!CGRectContainsPoint(self.containerView.frame, location)) {
        [self closeButtonTapped:nil];
    }
}

@end
